#!/usr/bin/env python

import sys
import os

import pickle
import select
import sys
import logging

from socket import *
from threading import *
from bluetooth import *

class BluetoothCommandServer:

    def __init__(self):
        
        print """
                #####################################
                # SERVER STARTED : MOBILE 2 SOCKET  #
                #####################################
                """
        self.server = None
        self.threads = []
        self.socketOutServer = SocketOutServer()

    def open_socket(self):
        
        try:
            self.server = BluetoothSocket(RFCOMM)
            self.server.bind(("",PORT_ANY))
            self.server.listen(5)
            self.port = self.server.getsockname()[1]
            self.uuid = "94f39d29-7d6d-437d-973b-fba39e49d4ee"
            advertise_service( self.server, "mobile2Socket",
                           service_id = self.uuid,
                           service_classes = [ self.uuid, SERIAL_PORT_CLASS ],
                           profiles = [ SERIAL_PORT_PROFILE ] )
        except socket.error, (value,message):
            if self.server:
                self.server.close()
            print "Could not open socket: " + message
            sys.exit(1)


    def run(self):
        self.open_socket()
        print "# Waiting for devices..."
        input = [self.server,sys.stdin]
        running = 1
        while running:
            inputready,outputready,exceptready = select.select(input,[],[])

            for s in inputready:

                if s == self.server:
                    # handle the server socket
                    c = BluetoothCommandDevice(self.socketOutServer, self.server.accept())
                    c.start()
                    self.threads.append(c)

                elif s == sys.stdin:
                    # handle standard input
                    junk = sys.stdin.readline()
                    running = 0 

        # close all threads

        self.server.close()
        for c in self.threads:
            c.join()

class BluetoothCommandDevice(Thread):

    def __init__(self,socketOutServer,(client,address)):
        Thread.__init__(self)
        self.client = client
        self.address = address
        self.size = 1024
        self.socketOutServer = socketOutServer
        self.device = BluetoothDevice(self.address[0], lookup_name(self.address[0], 10))
        self.socketOutServer.sendMessage(self.device.address + ",connect," + self.device.name + "\0")
        print "# Device connected: ", address


    def run(self):
        running = 1
        while running:
            try:
                self.data = self.client.recv(self.size)
                self.socketOutServer.sendMessage(self.address[0] + "," + self.data[2] + "\0")
            except:
                self.socketOutServer.sendMessage(self.address[0] + ",disconnect\0")
                print "# Device disconnected: ", self.address
                self.client.close()
                running = 0

class BluetoothDevice:
    
    def __init__(self,address, name):
        self.address = address
        self.name    = name

    def setMessage(self, message):
        self.message = str(message)


class SocketOutServer:
    
    def __init__(self):

        self.server = socket(AF_INET, SOCK_STREAM)
        self.server.bind(("", 8484))
        self.server.listen(5)
        print "# Waiting for the application..."
        self.client, self.addr = self.server.accept()
        print "# Application connected: ", self.addr

    def sendMessage(self, message):
            try:
                print "# Send socket message: ", message
                self.client.send(str(message))
            except:
                print "# Socket disconnect: ", self.addr
                self.client.close()


if __name__ == "__main__":
    s = BluetoothCommandServer()
    s.run()
